package com.wxyzz.satserver.pay.service.impl;


import com.wxyzz.common.core.entity.DropOrder;
import com.wxyzz.satserver.droporder.service.DropOrderService;
import com.wxyzz.satserver.pay.param.OrderPayParam;
import com.wxyzz.satserver.pay.param.PayParam;
import com.wxyzz.satserver.pay.service.OrderPayService;
import com.wxyzz.satserver.pay.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

@Service
public class OrderPayServiceImpl implements OrderPayService {

    // @Resource(name = "aliPayServiceImpl")
    @Autowired
    @Qualifier("aliPayServiceImpl")
    private PayService aliPayService;

    @Resource(name = "wxPayServiceImpl")
    private PayService wxPayService;

    @Resource
    private DropOrderService dropOrderService;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public String createOrderPay(OrderPayParam orderPayParam) {
        // 根据orderNo查询订单的信息，本例省略

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");

        PayParam param = new PayParam();
        // param.setOrderNo(sdf.format(new Date()));
        param.setOrderNo(orderPayParam.getOrderNo());
        param.setSubject("测试支付");
        param.setTotalAmount(new BigDecimal("0.01"));

        String url = "";
        if (orderPayParam.getPayPlatform().equals(2)) {
            url = aliPayService.createPay(param);
        } else {
            url = wxPayService.createPay(param);
        }

        // 生成交易订单后，将数据存入掉单表
        DropOrder dropOrder = new DropOrder();
        dropOrder.setOrderNo(orderPayParam.getOrderNo());
        dropOrder.setPlatform(orderPayParam.getPayPlatform());
        dropOrderService.addDropOrder(dropOrder);

        return url;
    }

    @Override
    public void orderNotify(HttpServletRequest request, HttpServletResponse response) {
        // 需要进行判断，判断是哪种支付的回调
        String orderNo = request.getParameter("orderNo");
        if (StringUtils.hasLength(orderNo)) {
            aliPayService.notify(request, response);
        } else {
            wxPayService.notify(request, response);
        }
    }

    @Override
    public void payStatus(OrderPayParam orderPayParam) {
        if (orderPayParam.getPayPlatform().equals(2)) {
            aliPayService.status(orderPayParam.getOrderNo());
        } else {
            wxPayService.status(orderPayParam.getOrderNo());
        }
    }

    @Override
    public void payClose(OrderPayParam orderPayParam) {
        if (orderPayParam.getPayPlatform().equals(2)) {
            aliPayService.close(orderPayParam.getOrderNo());
        } else {
            wxPayService.close(orderPayParam.getOrderNo());
        }
    }

    @Override
    public void orderReturn(HttpServletRequest request, HttpServletResponse response) {
        aliPayService.returnNotify(request, response);
    }

    @Override
    public void dropOrderLoop() {
        List<DropOrder> dropOrders = dropOrderService.selectList();
        if (dropOrders != null && dropOrders.size() > 0) {
            dropOrders.forEach(item -> {
                // 线程池进行异步执行
                threadPoolExecutor.execute(() -> {
                    OrderPayParam param = new OrderPayParam();
                    param.setOrderNo(item.getOrderNo());
                    param.setPayPlatform(item.getPlatform());
                    try {
                        // 获取交易订单状态，没有报异常，说明支付完成
                        payStatus(param);
                        // 修改业务订单的一些字段，比如支付状态

                        dropOrderService.deleteById(item.getId());
                    } catch (Exception e) { // 说明没有正常支付
                        Integer num = item.getNum();
                        if (num < 10) {
                            // 说明没有达到最大轮询次数，次数+1，继续轮询
                            dropOrderService.updateNum(item.getId(), item.getNum());
                        } else {
                            // 达到最大轮询次数，说明支付出问题，或者客户中断支付
                            dropOrderService.deleteById(item.getId());
                            payClose(param);
                            // 修改业务订单的状态 关闭状态
                        }
                    }
                });

            });
        }
    }
}
